<script setup>

	import { ref, onMounted, watch, nextTick, markRaw, defineAsyncComponent, getCurrentInstance } from "vue";
	//==============================vant组件
	import { Button, showToast } from 'vant';

	import login from "./pages/login.vue";

	import { store, loginOpen } from './js/store.js';
	import { Router, topage } from "./js/hashRouter.js";

	const vm = getCurrentInstance();//获取组件实例

	// 使用import.meta.glob批量导入views目录下的所有.vue文件，实现自动加载页面组件
	const vueFiles = import.meta.glob(`/src/views/*.vue`);
	const dirFiles = import.meta.glob(`/src/views/**/*.vue`);
	const viewsFiles = { ...vueFiles, ...dirFiles };
	// views对象，用于存储路由页面的组件
	const views = ref({});
	for (const [key, promise] of Object.entries(viewsFiles)) {
		// 提取文件名（去掉路径和扩展名）
		const fileName = key.split('/').pop().split('.')[0];
		// 将组件转换为异步组件并标记为原始对象（防止复用带来的副作用）
		views.value[fileName] = markRaw(defineAsyncComponent(() => promise()));
	}

	const hashActive = ref(null);
	const frame = ref(true);//主框架是否显示
	const menu = ref(false);//仅显示按钮框架
	// 当前显示的组件标记
	const currentCom = ref('first');
	// 两个组件的引用
	const currentViewFirst = ref(null);
	const currentViewSecond = ref(null);
	const currentViewFirstKey = ref(null);
	const currentViewSecondKey = ref(null);
	const firstComponent = ref(null);
	const secondComponent = ref(null);
	//刷新控制（需处理子组件重复挂载事件）
	const uniqueKey1 = ref(null);
	const uniqueKey2 = ref(null);


	const page_an = ref({in:'animate__fadeInRight',out:'animate__zoomOutDown'})

	//setup内方法
	onMounted(() => {
		// 动画结束后事件
		firstComponent.value.addEventListener('animationend', element => {
			if (element.target.classList.contains(page_an.value.out)) {
				element.target.style.display = 'none';
			}
		});
		secondComponent.value.addEventListener('animationend', element => {
			if (element.target.classList.contains(page_an.value.out)) {
				element.target.style.display = 'none';
			}
		});
	});

	var historyUrl = [];
	//路由功能
	const pageRouter = store.pageRouter = new Router();
	pageRouter.init();

	//针对全部路由添加监听
	pageRouter.route("hash", function (hash, currentUrl, ev) {
		// 含多个路由的数组，component展示最后一个，其它自行处理或单独写route()
		var _hash = hash[hash.length - 1];
		var _page = views.value[_hash];
		if(!pageRouter.routes[_hash] || !pageRouter.routes[_hash].sub){ //路由是（/frame/**）显示主框架
			frame.value = hash.length>1 && hash[0]=='frame' ? true : false;
			menu.value = hash.length>1 && hash[0]=='menu' ? true : false;
		}
		hashActive.value = _hash;
		const isBack = historyUrl.length>=2 && historyUrl[historyUrl.length-2]==ev.newURL && historyUrl[historyUrl.length-1]==ev.oldURL;
		isBack ? historyUrl.pop() : historyUrl.push(ev.newURL);
		if (_page) {
			switchComponent(hashActive.value, _page, !isBack); // !isBack 后退不刷新
		}

	});

	// 移动端双组件切换模式，使用animate.css动画切换页面
	// 若想只挂在一个component组件，参考https://gitee.com/flashme/vite-elementplus-cli
	// （其它如vue-router框架方式自行查找）
	// 切换组件的方法
	function switchComponent(newHash, _page, refresh) {
		// 如果当前路由已显示则保持当前组件呈现，不切换显示
		if(currentCom.value == 'second' && currentViewSecond.value == _page){
			currentCom.value = 'first';
		}else if(currentCom.value == 'first' && currentViewFirst.value == _page){
			currentCom.value = 'second';
		}
		// 双组件切换
		if (currentCom.value === 'first') {
			// 如果当前显示的是第一个组件，则切换到第二个组件
			currentCom.value = 'second';
			currentViewSecond.value = _page;
			currentViewSecondKey.value = newHash;
			secondComponent.value.style.display = 'block';
			uniqueKey2.value = null;
			// nextTick(() => {
			// 	refresh && (uniqueKey2.value = Date.now());
			// });
		} else {
			// 如果当前显示的是第二个组件，则切换到第一个组件
			currentCom.value = 'first';
			currentViewFirst.value = _page;
			currentViewFirstKey.value = newHash;
			firstComponent.value.style.display = 'block';
			uniqueKey1.value = null;
			// nextTick(() => {
			// 	refresh && (uniqueKey1.value = Date.now());
			// });
		}
	}

	//针对登录路由添加监听
	pageRouter.route("login", function (path) {
		hashActive.value = path;
		loginOpen.popup = true;
	}, function () {
		loginOpen.popup = false;
	});
	pageRouter.routes['login'].sub = true;

	if(!location.hash){
		topage(store.homehash);
	}else{
		store.pageOpen = location.hash;
	}
	function onBack() {
		if(location.hash == '#'+store.homehash){
			return;
		}else if(store.pageOpen == location.hash){
			store.pageOpen = '';
			location.hash = '#'+store.homehash;
			return;
		}
		window.history.back();
	}
	store.onBack = onBack;

	//监听login变化
	watch(() => loginOpen.user, (newVal, oldValue) => {
		if (newVal) {
		}
	})
	function loginClose() {
		if (window.location.hash == '#/login') {
			topage(store.homehash);
		}
	}

</script>


<template>

	<div class="wrap">
		<header v-if="frame"><div class="dt"><div class="back" @click="onBack"><svgIcon name="back"></svgIcon></div></div>{{store.title}}</header>
		<div class="main pile">
			<!-- 第一个组件 -->
			<div ref="firstComponent" :class="['page animate__animated animate__faster',currentCom === 'first'?page_an.in:page_an.out]">
				<keep-alive max="5">
					<component :is="currentViewFirst" :title="currentViewFirstKey" :key="uniqueKey1" />
				</keep-alive>
			</div>
			<!-- 第二个组件 -->
			<div ref="secondComponent" :class="['page animate__animated animate__faster',currentCom === 'second'?page_an.in:page_an.out]">
				<keep-alive max="5">
					<component :is="currentViewSecond" :title="currentViewSecondKey" :key="uniqueKey2" />
				</keep-alive>
			</div>

		</div>

		<div id="menu" class="flexrow justify-evenly" v-if="frame||menu">
			<li @click="topage('/menu/home', {pTitle:'首页'})" :class="[{active:hashActive=='home'}]"><i><svgIcon name="home"></svgIcon></i>首页</li>
			<li @click="topage('/frame/me', {pTitle:'我的'})" :class="[{active:hashActive=='me'}]"><i><svgIcon name="me"></svgIcon></i>我的</li>
		</div>
	</div>

	<van-popup v-model:show="loginOpen.popup" @close="loginClose" :style="{ padding: '20px' }">
		<login title="登陆" />
	</van-popup>

</template>

<style>
	#app {
		width: 100%;
		height: 100%;
	}

	.pile {
		overflow: hidden;
	}

	.page {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		-webkit-overflow-scrolling: touch;
	}
</style>